package com.cup.bddm.config;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.servlet.ModelAndView;

import com.cup.bddm.api.controller.BaseController;
import com.cup.bddm.api.res.ResVo;
import com.cup.bddm.util.JsonUtil;

/**
 * 处理400 404 405 500错误
 */
public class DispatcherServlet extends org.springframework.web.servlet.DispatcherServlet {

	private static final long serialVersionUID = 1793425145424034236L;

	@Override
	protected ModelAndView processHandlerException(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) throws Exception {
		if (ex instanceof HttpMessageNotReadableException) {
			writeRes(req, res, "400 BAD REQUEST! " + ex.getMessage());
		} else if (ex instanceof ServletRequestBindingException) {
			writeRes(req, res, "400 REQUEST PARAMS ERROR! " + ex.getMessage());
		} else if (ex instanceof HttpRequestMethodNotSupportedException) {
			writeRes(req, res, "405 METHOD NOT SUPPORTED! " + ex.getMessage());
		} else
			logger.error("500 SERVER ERROR!", ex);
			writeRes(req, res, "500 SERVER ERROR! " + ex.getMessage());
		return null;
	}

	@Override
	protected void noHandlerFound(HttpServletRequest req, HttpServletResponse res) throws Exception {
		writeRes(req, res, "404 NOT FOUND!");
	}

	private void writeRes(HttpServletRequest req, HttpServletResponse res, String msg) {
		res.setCharacterEncoding("UTF-8");
		res.setContentType("application/json; charset=UTF-8");
		try {
			String json = JsonUtil.toJson(ResVo.err(msg));
			req.setAttribute(BaseController.RES_BODY, json);
			PrintWriter w = res.getWriter();
			w.write(json);
			w.flush();
			w.close();
		} catch (IOException e) {
			logger.error(e);
		}
	}

}
